import { defineStore } from 'pinia';
import { store } from '/@/store';
import { FLOWRELEASE_KEY } from '/@/enums/cacheEnum';
import { closeFlowProcessApi } from '/@/api/flow/flow';
import { createLocalStorage } from '/@/utils/cache';

const ls = createLocalStorage();

const flowReleaseParams = ls.get(FLOWRELEASE_KEY) || '';

interface FlowParams {
  workItemId: number;
  entryId: number;
  userId?: number;
}

interface FlowGuid {
  guid: string;
}

type FlowReleaseParams = FlowParams & FlowGuid;

interface FlowState {
  flowParams: Nullable<FlowParams>;
  flowReleaseParams: Nullable<FlowReleaseParams>;
}

export const useFlowStore = defineStore({
  id: 'app-flow',
  state: (): FlowState => ({
    flowParams: null,
    flowReleaseParams,
  }),
  getters: {
    getFlowParams(): FlowParams | null {
      return this.flowParams;
    },
    getFlowReleaseParams(): FlowReleaseParams | null {
      return this.flowReleaseParams;
    },
  },
  actions: {
    setFlowParams(params: FlowParams | null) {
      this.flowParams = params;
    },
    setFlowReleaseParams(params: FlowReleaseParams | null) {
      this.flowReleaseParams = params;
      ls.set(FLOWRELEASE_KEY, params);
    },
    async releaseFlowProcess(params: FlowReleaseParams) {
      await closeFlowProcessApi(params);
      this.setFlowReleaseParams(null);
    },
  },
});

export function useFlowStoreWithout() {
  return useFlowStore(store);
}
